<template>
  <ul>
    <li :style="{ display: item.hasChildren ? '' : 'inline-block' }" v-for="item in list" :key="item.id">
      <el-checkbox :label="item.value">{{ item.title }}</el-checkbox>
      <el-button v-if="item.hasChildren" @click="selectAll(item)" type="text">全 选</el-button>
      <item v-if="item.hasChildren" :list="item.children" @change="handleItemChange" :value="value"></item>
    </li>
  </ul>
  <!-- <td>
    <table class="node" cellspacing="0" cellpadding="0" border="1"
      style="border-collapse: collapse; border-width: 0px; border-style: hidden">
      <tr v-for="item in list" :key="item.id" v-if="list.length > 0">
        <td class="node-title">
          <el-checkbox class="node-title-checkbox" :label="item.value" :key="item.value">{{ item.title }}</el-checkbox>
          <el-button v-if="item.hasChildren" @click="selectAll(item)" type="text">全 选</el-button>
        </td>
        <item :list="item.children" v-if="item.hasChildren" @change="handleItemChange" :value="value"></item>
      </tr>
    </table>
  </td> -->
</template>

<script>
export default {
  name: "item",
  props: {
    list: [],
    value: {
      type: Array,
      required: true,
    },
  },
  data() {
    return {}
  },
  methods: {
    handleItemChange(ids) {
      this.$emit("change", ids)
    },
    recursion(list) {
      let ids = []
      if (list.length > 0) {
        list.forEach((v) => {
          ids.push(v.value)
          if (v.hasChildren) {
            ids = ids.concat(this.recursion(v.children))
          }
        })
      }
      return ids
    },
    selectAll(menu) {
      if (!this.value.includes(menu.value)) {
        // 选中
        if (menu.hasChildren) {
          let ids = []
          ids = this.recursion(menu.children)
          ids.push(menu.value)
          ids = Array.from(new Set(this.value.concat(ids)))
          this.$emit("change", ids)
        }
      } else {
        // 反选
        if (menu.hasChildren) {
          let ids = []
          ids = this.recursion(menu.children)
          ids.push(menu.value)
          ids = this.value.filter((v) => !ids.includes(v))
          this.$emit("change", ids)
        }
      }
    },
  },
}
</script>
